import http from '../../http'

export default {
   namespaced:true,
   state:{
      // 分类列表
      classifyList:[],
      // 购物车列表
      shopList:[]
   },
   getters:{
      // 总数量
      allCount(state){
         return state.shopList.reduce((prev,next)=>{
            return prev+next.count
         },0)
      },
      // 总价格
      allCount(state){
         return state.shopList.reduce((prev,next)=>{
            return prev+next.count*next.price
         },0)
      },
   },
   mutations:{
      // 添加商品
      addItem(state,action){
         let flag =state.shopList.some(item=>item.id===action.id)
         if(flag){
            action.count+=1
         }else{
            state.shopList.push(action)
         }
      },
      // 初始化赋值
      setClassify(state,action){
         state.classifyList=action.list
      },
      // +
      addCarItem(state,action){
         state.shopList[action.index].count+=1
      },
      // -
      remCarItem(state,{rem,index}){
         if(rem){
            state.shopList.splice(index,1)
         }else{
            state.shopList[index].count-=1
         }
      }
   },
   // 处理异步任务
   actions:{
      init({commit}){
         http.get('/getList').then(res=>{
            commit('setClassify',{list:res.data.data})
         })
      }
   }
}